package life.fairy.community.controller;

import life.fairy.community.dto.NotificationDTO;
import life.fairy.community.dto.PaginationDTO;
import life.fairy.community.mapper.UserMapper;
import life.fairy.community.model.User;
import life.fairy.community.service.NotificationService;
import life.fairy.community.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName ProfileController
 * @Description TODO
 * @date 2021/4/5 11:17
 * @Version 1.0
 */
@Controller
public class ProfileController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private NotificationService notificationService;

    @GetMapping("/profile/{action}")
    public String profile(@PathVariable(name = "action") String action,
                          Model model,
                          HttpServletRequest request,
                          @RequestParam(name = "page", defaultValue = "1") Integer page, // 获取的参数 显示的page
                          @RequestParam(name = "size", defaultValue = "10") Integer size  // 获取的参数 每一页显示的数据量
    ) {

        User user = (User)request.getSession().getAttribute("user");

        if (user == null) {
            return "redirect: /";
        }

        if ("questions".equals(action)) {
            model.addAttribute("section", "questions");
            model.addAttribute("sectionName", "我的提问");

            PaginationDTO paginationDTO = questionService.list(user.getId(), page, size);
            model.addAttribute("pagination", paginationDTO);
        } else if ("replies".equals(action)) {
            PaginationDTO paginationDTO = notificationService.list(user.getId(), page, size);
            Long unreadCount = notificationService.unreadCount(user.getId());
            model.addAttribute("section", "replies");
            model.addAttribute("pagination", paginationDTO);
            /*已通过session方式获取并传递
            model.addAttribute("unreadCount", unreadCount);
            */
            model.addAttribute("sectionName", "最新回复");
        }

        return "profile";
    }
}
